<?php
declare (strict_types = 1);

namespace app\admin\controller;

use think\Request;
use app\BaseController;
use think\exception\ValidateException;

use app\common\validate\AdminValidate;

use app\common\model\Admin;
use think\facade\Session;

class LoginController extends BaseController
{
    /** 登陆页面渲染 */
    public function login()
    {
        return view();
    }

    /** 登陆 */
    public function login_data()
    {
    	if(request()->isPost()){
            $data = input('post.');

            // 验证数据
            try{
                validate(AdminValidate::class)->scene('login')->check($data);
            }catch(ValidateException $e){
                $this->error_back($e->getError());
            }

            $adminModel = new Admin();
            $info = $adminModel->getFind(['username' => $data['username']]);

            if($info['code'] != 'ok'){
                $this->error_back('该账号不存在');
            }

            if($info['data']['password'] != setPass($data['password'])){
                $this->error_back('密码错误');
            }

            $infoArr = $info['data']->toArray();
            Session::set('token', $infoArr);

	        $this->success_back('登陆成功');
	    }

        return view();
    }

    /** 退出登陆 */
    public function login_out()
    {
        Session::delete('token');
        return view('login/login');
    }
}
